from DBMoodls.User import User
from routes.app import db
from datetime import datetime


class UserService:

    def get_user(self, username, password):
        """

        :param username: 账号
        :param password: 密码
        :return: user对象
        """
        user = db.session.query(User).filter_by(username=username, password=password).first()
        print(user.uid,user.username, user.password)
        return user

    def add_user(self, username, password):
        """

        :param username:
        :param password:
        :return:
        """
        created_at = self.get_current_time()
        updated_at = self.get_current_time()
        user = User(username=username, password=password, created_at=created_at, updated_at=updated_at)
        db.session.add(user)
        db.session.commit()
        return user

    def get_current_time(self):
        """
        获取当前时间
        :return:
        """
        return datetime.now()

    def update_user(self,uid,new_username,new_password):
        """
        更新用户信息
        :param uid:
        :param new_username:
        :param new_password:
        :return:
        """
        user = db.session.query(User).filter_by(uid=uid).first()
        user.username=new_username
        user.password=new_password
        db.session.commit()
        return user

    def get_user_by_username(self, username):
        """
        根据用户名获取用户

        :param username: 用户名
        :return: User 对象或 None
            """
        user = db.session.query(User).filter_by(username=username).first()
        return user